package com.datang.pet.service.impl;/*
 * @auther 顶风少年
 * @mail dfsn19970313@foxmail.com
 * @date 2019-06-27 13:04
 * @notify
 * @version 1.0
 */

import com.alibaba.fastjson.JSON;
import com.datang.pet.common.redis.RedisTool;
import com.datang.pet.common.socket.WebSocketServer;
import com.datang.pet.common.utils.StringUtils;
import com.datang.pet.mapper.ChatMapper;
import com.datang.pet.mapper.UserInfoMapper;
import com.datang.pet.mapperExtend.ChatMapperExtend;
import com.datang.pet.pojo.*;
import com.datang.pet.service.ChatService;
import com.datang.pet.vo.GetUserChatListResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

@Service
public class ChatServiceImpl implements ChatService {
    //异常写入日志
    private static final org.slf4j.Logger log = org.slf4j.LoggerFactory.getLogger(ChatServiceImpl.class);

    @Autowired
    private ChatMapper chatMapper;
    @Autowired
    private RedisTool redisTool;

    @Autowired
    private WebSocketServer webSocketServer;

    @Autowired
    private ChatMapperExtend chatMapperExtend;

    @Autowired
    private UserInfoMapper userInfoMapper;

    /*
     * @author 顶风少年
     * @date 2019/6/27 13:11
     * @mail dfsn199703132038@foxmail.com
     * @throws
     * @param
     * @param chat
     * @result void
     * @notify 发送消息
     * version 1.0
     */
    @Transactional(rollbackFor = Exception.class)
    public void addChat(Chat chat) throws Exception {
        //从redis中查询是否有用户id
        String redisUserId = (String) redisTool.get(chat.getConsigneeId());
        //发送人id
        String sendUserId = chat.getSenderId();
        //接收人id
        String consigneeUserId = chat.getConsigneeId();

        //a和b的id连接.到数据库查询.
        ArrayList<String> ids = new ArrayList<>();
        ids.add(sendUserId + consigneeUserId);
        ids.add(consigneeUserId + sendUserId);

        ChatExample chatExample = new ChatExample();
        ChatExample.Criteria criteria = chatExample.createCriteria();

        criteria.andIdIn(ids);

        List<Chat> chats = chatMapper.selectByExample(chatExample);

        //如果查不到说明两人第一次回话.增加一个回话id
        if (chats.isEmpty()) {
            chat.setId(sendUserId + consigneeUserId);

        } else {
            //如果有回话则使用之前的回话id
            chat.setId(chats.get(0).getId());
        }
        if(redisUserId==null){
            chat.setIsRead("0");
        }else{
            chat.setIsRead("1");
        }
        chat.setMessageDate(new Date());
        try {
            chatMapper.insert(chat);
        } catch (Exception e) {
            throw new Exception("添加消息失败");
        }


        if (redisUserId != null) {
            Map<String, Object> map = new HashMap<>();
            if (chats.isEmpty()) {
                //新增消息
                GetUserChatListResponse getUserChatListResponse = new GetUserChatListResponse();
                //添加id
                getUserChatListResponse.setId(sendUserId + consigneeUserId);
                //添加头像昵称
                UserInfo userInfo = userInfoMapper.selectByPrimaryKey(chat.getSenderId());
                getUserChatListResponse.setHeadPortrait(userInfo.getHeadPortrait());
                getUserChatListResponse.setNikeName(userInfo.getNikeName());
                getUserChatListResponse.setMessageDate(chat.getMessageDate());
                getUserChatListResponse.setUserId(chat.getSenderId());

                //添加子信息
                List<Chat> chatList = new ArrayList<>();
                chatList.add(chat);
                getUserChatListResponse.setChatList(chatList);

                map.put("addChat", getUserChatListResponse);
            } else {
                //追加消息
                map.put("putChat", chat);
            }


            try {
                String jsonDate = JSON.toJSONString(map);
                webSocketServer.sendMessage(jsonDate, chat.getConsigneeId());
            } catch (Exception e) {
                log.error("给用户发送消息失败");
            }
        }
    }


    /*
     * @author 顶风少年
     * @date 2019/6/27 13:45
     * @mail dfsn199703132038@foxmail.com
     * @throws
     * @param
     * @param consigneeId
     * @param senderId
     * @result java.util.List<com.datang.pet.vo.GetUserChatListResponse>
     * @notify 查询用户消息
     * version 1.0
     */
    public List<GetUserChatListResponse> getUserChatList(String userId, Date time) throws Exception {
        try {
            List<GetUserChatListResponse> userChatList = chatMapperExtend.getUserChatList(userId, time);
            //给每个通讯 增加 子消息
            for (GetUserChatListResponse getUserChatListResponse : userChatList) {
                Chat chat = new Chat();
                chat.setId(getUserChatListResponse.getId());
                List<Chat> chatList = getChatList(chat);
                getUserChatListResponse.setChatList(chatList);
            }
            return userChatList;
        } catch (Exception e) {
            throw new Exception("获取消息失败");
        }
    }

    /*
     * @author 顶风少年
     * @date 2019/6/27 13:47
     * @mail dfsn199703132038@foxmail.com
     * @throws
     * @param
     * @param chat
     * @result java.util.List<com.datang.pet.pojo.Chat>
     * @notify 获取聊天记录
     * version 1.0
     */
    public List<Chat> getChatList(Chat chat) throws Exception {
        try {
            List<Chat> chatList = chatMapperExtend.getChatList(chat);
            List<String> ids = new ArrayList<>();
            for(Chat c:chatList){
                ids.add(c.getId());
            }
            ChatExample chatExample = new ChatExample();
            ChatExample.Criteria criteria = chatExample.createCriteria();
            criteria.andIdIn(ids);
            Chat c = new Chat();
            c.setIsRead("1");
            chatMapper.updateByExampleSelective(c,chatExample);
            return chatList;
        } catch (Exception e) {
            throw new Exception("获取单个用户聊天记录失败");
        }

    }
}
